﻿using App.Core._MockData;
using App.Core.Data;
using App.Core.Entities;
using App.Core.Services;
using AppTemplate.Infrastructure.DependencyInjection;
using AppTemplate.Infrastructure.Paging;
using AppTemplate.Infrastructure.ServiceBase;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace App.Core.ServiceImpls
{
    [Inject(LifeTime =InjectionLifeTime.Transient)]
    public class MockDataUserService : ServiceBase<User>, IUserService
    {
        public MockDataUserService(AppDbContext dbContext) : base(dbContext)
        {

        }

        public async Task<User?> Auth(string username, string password)
        {
            await Task.Delay(2000);//模拟耗时
            return MockUserData.Users.First();
        }

        public Task<User?> GetUserByAccount(string account)
        {
            return Task.Run(() => MockUserData.Users.FirstOrDefault(x => x.Account == account));
        }

        public async Task<PageSearchResult<User>> PageSearch(int pageIndex, int pageSize, string? account = null, string? name = null)
        {
            Expression<Func<User, bool>> predicateExp = PredicateBuilder.New<User>(true);
            if (!string.IsNullOrEmpty(account))
            {
                predicateExp = predicateExp.And(u => u.Account == account);
            }
            if (!string.IsNullOrEmpty(name))
            {
                predicateExp = predicateExp.And(u => u.Name == name);
            }

            if (pageIndex <= 0)
                pageIndex = 1;
            if (pageSize <= 0)
                pageSize = 20;
            var predicate = predicateExp.Compile();

            var totalCount = MockUserData.Users.Where(predicate).Count();
            var result = MockUserData.Users.Where(predicate).Skip((pageIndex - 1) * pageSize).Take(pageSize);

            await Task.Delay(2000);//模拟耗时

            return new PageSearchResult<User> { Data = result, Total = totalCount };
        }
    }
}
